package com.elong.android.specialhouse.utils;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

/**
 * 类型功能说明描述
 *
 * @author cheng.wang
 * @date 2015/11/17 11:14
 */
public class NetUtils {
    /**
     * 检查网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean checkIsWifiEnable(Context context) {
        NetworkInfo networkInfo = ((ConnectivityManager) context.
                getSystemService(Activity.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if ((networkInfo != null) && networkInfo.isAvailable()) {
            return networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
        }
        return false;
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    public static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    /**
     * 获取当前ip地址
     *
     * @param context
     * @return
     */
    public static String getIpAddress(Context context) {
        try {
            if (checkIsWifiEnable(context)) {
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int i = wifiInfo.getIpAddress();
                return int2ip(i);
            } else {
                return "0.0.0.0";
            }
        } catch (Exception ex) {
            return "0.0.0.0";
        }
    }
}